package com.blogWebAutoTest.common;

import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.chrome.ChromeDriver;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author YuanYuan
 * @Date 2023/2/12
 * @Time 11:35
 */
public class AutoTestUtils {
    private static ChromeDriver driver;

    //创建驱动对象
    public static ChromeDriver chromeDriver() {
        //驱动对象已经创建好了/没有创建
        if(null == driver){
            driver = new ChromeDriver();
            //创建隐式等待
            driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));
        }
        return driver;
    }

    /*
     * 拿到时间
     * @return
    */
    private static List<String> getTime() {
        //文件夹名称
        SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyyMMdd");
        //图片名称
        SimpleDateFormat simpleDateFormat2 = new SimpleDateFormat("yyyyMMdd-HHmmSS");
        String dirname = simpleDateFormat1.format(System.currentTimeMillis());
        String filename = simpleDateFormat2.format(System.currentTimeMillis());
        //存到链表里返回
        List<String> list = new ArrayList<>();
        list.add(dirname);
        list.add(filename);
        return list;
    }
    /*
     * 获取屏幕截图,把所有用例的截图结果保存下来
     * @return
    */
    public static void getScreenShor(String methodname) throws IOException {
        List<String> list = getTime();
        //取到目录时间和文件命名时间
        String dirtime = list.get(0);
        String filetime = list.get(1);
        //给文件按照时间戳命名
        //./是当前路径名,就是BlogAutoTest
        String filename = "./src/test/java/com/blogWebAutoTest/" + dirtime +"/"+methodname+ "-" +filetime +".png";
        //获取文件
        File file = driver.getScreenshotAs(OutputType.FILE);
        //将文件放到指定路径下并命名
        FileUtils.copyFile(file,new File(filename));
    }
}
